from google.appengine.ext import webapp 
from google.appengine.api import taskqueue
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler 
from google.appengine.ext.webapp.util import run_wsgi_app

from google.appengine.api import mail


import logging
import email
import string 
import cachedstore

from models import *
from updatetasks import *
from datetime import *

class LogSenderHandler(InboundMailHandler):
    def receive(self, email): 
          
        logging.info("Incoming email from %s", email.sender)
        
        emailcheck = email.sender.lower()        
        if not "action@ifttt.com" in emailcheck:
            logging.warn("Email from unapproved sender %s! Skipping processing", emailcheck)
            return
        
        keyName = email.subject     
        bodies = email.bodies('text/plain')
        for content_type, body in bodies:
            feedUrl = body.decode()
               
        logging.debug("Received IFTT email for %s, feed %s", keyName, feedUrl)
       
        periodical = Periodical.get_by_key_name(keyName)        
        if periodical:            
            logging.debug("Updating feed updated date for %s", keyName)   
            periodical.feedUpdated = datetime.now()
            periodical.feed = feedUrl
            periodical.put()
        
application = webapp.WSGIApplication([LogSenderHandler.mapping()], debug=True)

def main():
   run_wsgi_app(application)
 
if __name__ == '__main__':
    main()